var MultipleMove = false ; //true时为双击时移过来，false时为复制过来
/**
chenjing 2009-5-13	表单相关操作的jquery扩展。
*/
jQuery.extend({
    evalJSON: function (strJson) {
        return Sys.Serialization.JavaScriptSerializer.deserialize(strJson);
    },
    //提交服务器的json字符串（服务器端可使用JavaScriptSerializer转义）
    toJSON: function (object) {
        return Sys.Serialization.JavaScriptSerializer.serialize(object);
    },
    //由js对象填充表单
    fillForm: function (obj, formblock) {
        //回填至数组对象
        if (typeof (obj.length) == "number") {
            $.each(obj, function (i, o) {
                $(formblock + " :text:eq(" + i + ")").val(o);
            });
            return obj;
        }

        $.each($(formblock + " label"), function (i, o) {
            var name = $(o).attr("name");
            if (typeof (obj[name]) == "undefined" || obj[name] == null) return;
            $(o).html(obj[name]);
        });

        $.each($(formblock + " :input"), function (i, o) {
            var name = $(o).attr("name");
            if (typeof (obj[name]) == "undefined" || obj[name] == null) return;
            switch (o.type) {
                case "select-one":
                    //ie特殊处理
                    window.setTimeout(function () { $(o).val(obj[name]) }, 300);
                    break;
                case "text":
                case "hidden":
                case "textarea":
                    var _v = String(obj[name]).replace(/&lt;/g, "<").replace(/&gt;/g, ">");
                    if (!isNaN((new Date(_v)).getYear())) {
                        if ($(o).attr("class").indexOf("time") != -1)
                            _v = (new Date(_v)).Format("yyyy-MM-dd hh:mm");
                        if ($(o).attr("class").indexOf("date") != -1)
                            _v = (new Date(_v)).Format("yyyy-MM-dd");
                        if ($(o).attr("class").indexOf("year") != -1)
                            _v = (new Date(_v)).Format("yyyy-MM-dd");
                    }
                    $(o).val(_v);
                    break;
                case "textarea":
                    var _v = String(obj[name]).replace(/&lt;/g, "<").replace(/&gt;/g, ">");
                    $(o).val(_v);
                    break;
                case "checkbox":
                case "radio":
                    var arr = String(obj[name]).split(",");
                    if ($.inArray(o.value, arr) != -1) o.checked = true;
                    break;
                case "select-multiple":
                    var arr = obj[name].split(",");
                    var src = $(":input[name=" + name + "_s]");
                    var tar = $(":input[name=" + name + "]");
                    $.each(src.children(), function (i, p) {
                        if ($.inArray(p.value, arr) != -1) {
                            if (MultipleMove) {
                                tar.append($(p));
                            }
                            else {
                                tar[0].options.add(new Option(p.text, p.value));
                            }
                        }
                    })
                    break;
            };
        });
    },
    //以baseparams填充select/checkbox选项
    fillItem: function (arr, inputName) {
        var obj = $(":input[name=" + inputName + "]");
        if (!obj[0]) return;
        switch (obj[0].type) {
            case "select-one":
            case "select-multiple":
                $.each(arr, function (i, o) {
                    obj.append('<option value="' + o.v + '">' + o.n + '</option>');
                });
                break;
            case "checkbox":
                $.each(arr, function (i, o) {
                    obj.parent().append('<input name="' + inputName + '" value="' + o.v + '" type="checkbox" id="' + inputName + i + '"><label for="' + inputName + i + '" title="">' + o.n + '</label>  ');
                });
                obj.remove();
                break;
            case "radio":
                $.each(arr, function (i, o) {
                    obj.parent().append('<input name="' + inputName + '" value="' + o.v + '" type="radio" id="' + inputName + i + '"><label for="' + inputName + i + '" title="">' + o.n + '</label>  ');
                });
                obj.remove();
                break;
        };
    },
    //由表单数据回填至js对象
    fillObj: function (obj, formblock) {
        var temp = [];
        //回填至数组对象
        if (typeof (obj.length) == "number") {
            obj = [];
            $.each($(formblock + " :text"), function (i, o) {
                switch (o.type) {
                    case "text":
                        if (o.value)
                            obj.push(o.value);
                        break;
                }
            });
            return obj;
        }
        $.each($(formblock + " :input"), function (i, o) {
            var name = $(o).attr("name");
            var type = typeof (obj[name]);
            if (type == "undefined") return;
            switch (o.type) {
                case "text":
                case "textarea":
                case "hidden":
                case "select-one":
                    if (!($(o).attr("escape") && $(o).attr("escape") == "false"))
                        obj[name] = o.value
										    .replace(/</g, "&lt;")
										    .replace(/>/g, "&gt;");
                    else
                        obj[name] = o.value;
                    break;
                case "checkbox":
                    if (type == "string" || !obj[name]) { obj[name] = []; temp.push(name); }
                    if (o.checked) obj[name].push($(o).val());
                    break;
                case "radio":
                    if (o.checked) obj[name] = o.value;
                    break;
                case "select-multiple":
                    obj[name] = [];
                    $.each(o.options, function (i, p) {
                        obj[name].push($(p).val());
                    });
                    temp.push(name);
                    break;
            }
        })
        $.unique(temp);
        $.each(temp, function (i, name) { obj[name] = obj[name].join(","); })
        return obj;
    },
    //从源Select控件双击选取option到目标Select控件
    multipleSelectLoad: function (tarName, scrName) {
        $(":input[name=" + scrName + "]").dblclick(function ()//源
        {
            if ($(this).attr("name") == scrName) {
                if (MultipleMove) {
                    $(":input[name=" + tarName + "]").append($(this).children(":selected"));
                }
                else {
                    var tarOption = $(this).children(":selected")[0];
                    if ($(':input[name=' + tarName + '] option[value=' + tarOption.value + ']').length == 0) {
                        $(":input[name=" + tarName + "]")[0].options.add(new Option(tarOption.text, tarOption.value));
                    }
                    else {
                        alert('已存在此项！');
                    }
                }
            }
            else//这里不知用来做什么的
            {
                if (MultipleMove) {
                    $(":input[name=" + scrName + "]").append($(this).children(":selected"));
                }
                else {
                    var op = $(this).children(":selected")[0];
                    $(":input[name=" + scrName + "]")[0].options.add(new Option(op.text, op.value));
                }
            }
        });
        $(":input[name=" + tarName + "]").dblclick(function ()//目标
        {
            if ($(this).attr("name") == tarName) {
                if (MultipleMove) {
                    $(":input[name=" + scrName + "]").append($(this).children(":selected"));
                }
                else {
                    $(this).children(":selected").remove();
                }
            }
            else//这里不知用来做什么的
            {
                if (MultipleMove) {
                    $(":input[name=" + tarName + "]").append($(this).children(":selected"));
                }
                else {
                    var op = $(this).children(":selected")[0];
                    $(":input[name=" + tarName + "]")[0].options.add(new Option(op.text, op.value));
                }
            }
        });
    },
    //带输入的select控件
    inputSelect: function (tarName, scrSelectName) {
        var src = $(":input[name=" + scrSelectName + "]");
        var tar = $(":input[name=" + tarName + "]");
        if (!(src[0] && tar[0])) return;
        src.change(function () {
            if (!this.value || this.value == "") {
                tar.val("");
                tar.css("display", "");
            }
            else {
                tar.css("display", "none");
                tar.val(this.value);
            }
        });
        if (src.children("[value=" + tar.val() + "]")[0]) {
            src.val(tar.val());
            return;
        }
        else {
            src.val("");
            tar.css("display", "");
        }
    },
    registerForm: function (formId, regexpObj) {
        $.each($("#" + formId + " :input"), function (i, o) {
            $(o).change(function () {
                $.checkInputValid(o, regexpObj);
            })
        })
    },
    resetForm: function (formId) {
        $("#" + formId + " :input[type!=button][type!=checkbox][type!=radio]").val('');
        $.each($("#" + formId + " :input[vinit]"), function (i, o) {
            $(this).val($(this).attr("vinit"));
        });
        $.each($("#" + formId + " :checkbox[vchecked],:radio[vchecked]"), function (i, o) {
            $(this).attr("checked", "checked");
        });
    },
    //chenjing 2010-2-21 新表单验证
    checkFormValid: function (formId, regexpObj, blockId) {
        var _blockId;
        if (!formId) _blockId = "frmEdit";
        if (formId) _blockId = formId;
        if (blockId) _blockId = blockId;
        $.showValidateState(1, formId);
        var valid = true;
        $.each($("#" + _blockId + " :input"), function (i, o) {
            if (!$.checkInputValid(o, regexpObj)) {
                valid = false;
            }
        });
        if (!valid) {
            $.showValidateState(3, formId);
            return false;
        }
        $.showValidateState(2, formId);
        return true;
    },
    //chenjing 2010-2-21 新输入项验证，支持正则或可以被初始化为正则对象的字符串，如
    /**
    var regexpObj = {
    tel1 : {   exp : /^[\d]{11}$/ ,   m : "请输入正确的手机号码，如13822556633" } ,
    tel2 : {   exp : '"^"+$(":input[name=tel1]").val()+"$"' ,   m : "两次输入的手机号不符" } 
    }
    */
    checkInputValid: function (o, regexpObj) {
        if (!regexpObj) {
            if (typeof (regular_input) == "undefined")
                return;
            regexpObj = regular_input;
        }
        var valid = true; var tar1, tar2;
        if (!$(o).attr('name') || typeof (regexpObj[$(o).attr("name")]) == "undefined")
            return true;
        switch (o.type) {
            case "text":
            case "file":
            case "textarea":
            case "password":
            case "hidden":
            case "select-one":
                var re = regexpObj[$(o).attr("name")].exp;
                if (typeof (re) == "string")
                    re = new RegExp(eval(regexpObj[$(o).attr("name")].exp));
                if (!o.value.match(re))
                    valid = false;
                break;
            case "radio":
            case "checkbox":
                if ($("input[name=" + $(o).attr('name') + "]:checked").length == 0)
                    valid = false;
                break;
        }
        if (!valid) {
            var errortxt = "<span class='explain' tar='" + $(o).attr("name") + "'>" + regexpObj[$(o).attr("name")].m + "</span>";
            $(o).parent().next().children(".tsxx").hide();
            $(o).parent().next().children(".explain[tar=" + $(o).attr("name") + "]").remove();
            $(o).parent().next().append(errortxt);
            return false;
        }
        else if ($(o).parent().next().children(".explain[tar=" + $(o).attr("name") + "]")[0]) {
            $(o).parent().next().children(".explain[tar=" + $(o).attr("name") + "]").remove();
            $(o).parent().next().children(".tsxx").show();
            return true;
        }
        else
            return true;
    },


    //chenjing 2010-2-21 新验证状态显示
    showValidateState: function (status, formId) {
        if (!formId) formId = "frmEdit";
        var img = '<img src="/css/cms/images/loading.gif"/>';
        switch (status) {
            case 1:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status .bbd-bj-bom").html("稍等，正在验证表单 " + img);
                $("#" + formId + " .main-status").css("display", "");
                break;
            case 2:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status .bbd-bj-bom").html("表单验证通过 " + img);
                $("#" + formId + " .main-status").css("display", "");
                window.setTimeout(function () { $.showValidateState(5, formId) }, 2000);
                break;
            case 3:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status .bbd-bj-bom").html("您的输入有误，请核对" + img);
                var sb = [];
                $.each($("#" + formId + " .explain"), function (i, n) {
                    sb.push((i + 1) + " : " + $(n).html() + "<p/>");
                });
                //popLayer.show("<font style='color:red'>错误提示！</font>", "<div style='text-align:left'>" + sb.join('') + "</div>", null, false);
                $("#" + formId + " .main-status").css("display", "");
                window.setTimeout(function () { $.showValidateState(5, formId) }, 2000);
                break;
            case 4:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status").css("display", "");
                $("#" + formId + " .main-status .bbd-bj-bom").html("信息正在提交，请稍候……" + img);
                break;
            case 5:
                $("#" + formId + " .main-status").css("display", "none");
                $("#" + formId + " .main-sub").css("display", "");
                break;
            case 6:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status").css("display", "");
                $("#" + formId + " .main-status .bbd-bj-bom").html("正在上传图片，请稍候……" + img);
                break;
            case 7:
                $("#" + formId + " .main-sub").css("display", "none");
                $("#" + formId + " .main-status").css("display", "");
                $("#" + formId + " .main-status .bbd-bj-bom").html("正在上传文件，请稍候……" + img);
                break;
        }
    },
    //还原字段的<>标记
    undoChHtmlTag: function (obj, params) {
        for (i = 0; i < params.length; i++) {
            obj[params[i]] = obj[params[i]].replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        }
        return obj;
    }

});




/**
chenjing 2007-11-6	
分页控件,调用getOutput()输出。callbackName定义翻页回调函数的名称
以下例子包含全部调用：
var turnPage_f;//全局变量
function aaa(){
turnPage_f = new TurnPage("turnPage_f");//实例化
reloadData();
}
function reloadData(){
turnPage_f.callbackName = "reloadData";//翻页回调函数的名称
var x=new AjaxRequest();
x.onresult=function(){
turnPage_f.total = x.getValue().total;//获取总数
$("dataDiv").innerHTML = turnPage_f.getOutput();//输出翻页
}
}
*/
function TurnPage(callerName)
{
	this.total = 0; //总记录数 

	this.pageSize = 10; //每页显示记录数
	this.currPage = 1; //当前页
	this.callback = function() { };

	this.showCurrPageCount = true; //是否显示页码
	this.currPageCount = 10; //每次显示10个页码


	this.pre = '<a title="上一页" id="scroll_prev" class="preview">上一页</a>';
	this.preHref = '<a title="上一页" id="scroll_prev" onclick="' + callerName + '.turn({#},true)" class="preview">上一页</a>';
	this.next = '<a id="scroll_next" class="preview">下一页</a>';
	this.nextHref = '<a title="下一页" id="scroll_next" onclick="' + callerName + '.turn({#},false)" class="next">下一页</a>';

	this.currPageStart = 1; //第一个页码

	this._isPre = false; //是否向前翻页
	this.show = function()
	{//是否显示翻页，总记录数为0时，不显示。

		if (this.total > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	};
	this.getPageCount = function()
	{
		if (this.total % this.pageSize > 0)
		{
			return parseInt(this.total / this.pageSize) + 1;
		}
		else
		{
			return parseInt(this.total / this.pageSize);
		}
	};
	this.getOutput = function()
	{
	    if(this.total == 0 || (this.getPageCount() == 1 && !this.showCurrPageCount))
	        return "";
		eval(callerName);
		var inner = [];
		inner.push('<span style="width:130px;">共'+this.getPageCount()+'页，'+this.total+'行记录</span>');
		//前页
		if (this.currPage == 1)
		{
			inner.push(this.pre);
		}
		else
		{
			inner.push(this.preHref.replace("{#}", this.currPage - 1));
		}
		//中段
		if (this.showCurrPageCount)
		{
			if (!this._isPre)
			{//向后翻页
				if (this.currPage % this.currPageCount == 1)
				{
					this.currPageStart = this.currPage;
				}
			}
			else
			{//向前翻页
				if (this.currPage % this.currPageCount == 0)
				{
					this.currPageStart = this.currPage - this.currPageCount + 1;
				}
			}
			var end = this.currPageStart - 1 + this.currPageCount;
			if (this.getPageCount() < end)
			{
				end = this.currPageStart - 1 + (this.getPageCount() % this.currPageCount);
			}
			if (this.total < this.pageSize)
			{
				end = 1;
			}
			for (i = this.currPageStart; i <= end; i++)
			{
				if (this.currPage == i)
					inner.push('<strong>' + i + '</strong>');
				else
				{
					inner.push('<a  href="javascript:void(0);" onclick="' + callerName + '.turn(' + i + ',false)" class="pages-active font-s">');
					inner.push(i);
					inner.push('</a>');
				}
			};
		}
		//后页
		if (this.currPage == this.getPageCount())
		{
			inner.push(this.next);
		}
		else
		{
			inner.push(this.nextHref.replace("{#}", this.currPage + 1));
		}
		return inner.join('');
	};
	this.turn = function(index, ispre)
	{
		this.currPage = index;
		this._isPre = ispre;
		this.callback.call();
	};
}

//绑定事件
function $addhandler(element, eventName, handler)
{
	var browserHandler;
	if (element.addEventListener)
	{
		browserHandler = function(e)
		{
			return handler.call(element, e);
		}
		element.addEventListener(eventName, browserHandler, false);
	}
	else if (element.attachEvent)
	{
		browserHandler = function()
		{
			return handler.call(element, window.event);
		}
		element.attachEvent('on' + eventName, browserHandler);
	}
}
//解除绑定事件
function $removehandler(element, eventName, handler)
{
	var browserHandler = null;
	if (element.removeEventListener)
	{
		browserHandler = function(e)
		{
			return handler.call(element, e);
		}
		element.removeEventListener(eventName, browserHandler, false);
	}
	else if (element.detachEvent)
	{
		browserHandler = function()
		{
			return handler.call(element, window.event);
		}
		element.detachEvent('on' + eventName, browserHandler);
	}
}

//计算剩余输入字符数
function loadnum(jo, jotar, num)
{
	jo.keyup(function()
	{
		var cur = eval(num - jo[0].value.length);
		jotar.html(cur);
		if (cur < 0) { jotar.html(0) }
	});
	if (jo[0]) { jotar.html(eval(num - jo[0].value.length)) }
}

function inputclear()
{
	$(":input.clear").each(function()
	{
	    var vinit = $.trim($(this).attr("vinit"));
		$(this).data("txt", vinit);
		if ($(this).val() == "" || $(this).val() == vinit)
		{
			$(this).val(vinit);
			$(this).css("color", "gray");
		}
	}).focus(function()
	{
		if ($.trim($(this).val()) === $(this).data("txt"))
		{
			$(this).val("");
			$(this).css("color", "");
		}
	}).blur(function()
	{
		if ($.trim($(this).val()) === "")
		{
			$(this).val($(this).data("txt"));
			$(this).css("color", "gray");
		}
	});

}


var piccheck = null;
function checkimg(obj)
{
	function getFullPath(obj)
	{
		if (obj)
		{
			//ie
			if (window.navigator.userAgent.indexOf("MSIE") >= 1)
			{
				obj.select();
				return document.selection.createRange().text;
			}
			//firefox
			else if (window.navigator.userAgent.indexOf("Firefox") >= 1)
			{
				return obj.files.item(0).getAsDataURL();
			}
		}
	}
	function SImage(callback)
	{
		var img = new Image();
		this.img = img;
		if (document.all)
		{
			//ie
			img.onreadystatechange = function()
			{
				if (img.readyState == "complete")
				{
					callback(img);
				}
			};
		} else
		{
			//firefox
			img.onload = function()
			{
				if (img.complete == true)
				{
					callback(img);
				}
			}
		}
	}

	SImage.prototype.get = function(url)
	{
		this.img.src = url;
	}
	function icall(obj)
	{
		if (obj.width > 400 && obj.width < 800 && obj.height > 300 && obj.height < 600)
		{
			piccheck = true;
		}
		else
		{
			alert("请上传宽度在400至800 像素之间，高度在300至600像素之间的图片。");
			piccheck = false;
		}


	}

	var img = new SImage(icall);
	img.get(getFullPath(obj));
}



function onsure(srcc, tar)
{
	srcc.click(function()
	{
		if (srcc.attr('checked') == true)
		{
			tar.removeAttr("disabled");
		}
		else
		{
			tar.attr("disabled", "true");
		}
	});
}

function initarea(areacode)
{
	var sheng = "<option value=''>请选择</option>", sheng_reg = /\d*-/;
	$.getJSON('/Scripts/mypage/area.txt', null, function(data)
	{
		$.each(data, function(entryIndex, entry)
		{
			var ln = entry['layno'], lr = entry['layrec'];
			if (ln == '1')
			{
				sheng += '<option value="' + lr + '"';
				if (areacode && areacode.match(new RegExp("^" + lr)))
				{
					sheng += " selected";
					initCity(lr);
				}
				sheng += '>' + entry['name'] + '</option>';
			}
		});
		$("select:[name=area1]").append(sheng);
		$("select:[name=area1]").change(function()
		{
			initCity(this.value);
		});
		function initCity(sheng)
		{
			var shi = "<option value=''>请选择</option>", shi_reg = /\d*-\d*-/;
			$("select:[name=area]").empty()
			$.each(data, function(entryIndex, entry)
			{
				var ln = entry['layno'], lr = entry['layrec'];
				if (ln == "2" && lr.match(new RegExp("^" + sheng)))
				{
					shi += '<option value="' + lr + '"';
					if (areacode && areacode.match(new RegExp("^" + lr)))
					{
						shi += " selected";
					}
					shi += '>' + entry['name'] + '</option>';
				}
			});
			$("select:[name=area]").append(shi);
		}
	});
}

function getTrade(tarC)
{
	var trade1 = "<option value=''>请选择</option>";
	$("select:[name=tradeid]").empty();
	$.getJSON('/Scripts/mypage/trade.txt', null, function(data)
	{
		$.each(data, function(entryIndex, entry)
		{
			var lp = entry['parentid'], id = entry['id'];
			if (lp == 0)
			{
				trade1 += '<option value="' + id + '"';
				if (tarC.tradeid && tarC.tradeid == id)
				{
					trade1 += " selected";
					initTrade2(id);
				}
				trade1 += '>' + entry['name'] + '</option>';
			}
		});
		$("select:[name=tradeid]").append(trade1);
		$("select:[name=tradeid]").change(function()
		{
			initTrade2(this.value);
		});
		function initTrade2(_pid)
		{
			var trade2 = "<option value=''>请选择</option>";
			$("select:[name=tradeid2]").empty()
			$.each(data, function(entryIndex, entry)
			{
				var lp = entry['parentid'], id = entry['id'];
				if (lp == _pid)
				{
					trade2 += '<option value="' + id + '"';
					if (tarC.tradeid2 && tarC.tradeid2 == id)
					{
						trade2 += " selected";
					}
					trade2 += '>' + entry['name'] + '</option>';
				}
			});
			$("select:[name=tradeid2]").append(trade2);
		}
	});
}

Date.prototype.Format = function(fmt) 
{ //author: meizz 
var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S" : this.getMilliseconds()             //毫秒 
}; 
if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
return fmt; 
}
